import { SearchOutlined } from "@ant-design/icons"
import { Button, Divider, Flex, Form } from "antd"
import dayjs from "dayjs"
import { FC, useCallback, useEffect, useState } from "react"

// import { queryTableList } from "@/api/member"
import { IMemberList } from "@/api/member/types"
import { IMemberParams } from "@/api/risk/types"
import { DataList, QueryForm, SFormItem } from "@/components/common"
import { Slot } from "@/components/common/slot"
import { CardContainer } from "@/components/common/styled"
import StyleSelect from "@/components/common/styleSelect"
import { Toast } from "@/components/messages"
import { useApi, useDigital, useLocale, usePagination } from "@/hooks"
import { FormatMessageProps } from "@/locales"
import {
	rangeCurrentMonth,
	rangeCurrentWeek,
	rangeLastMonth,
	rangeLastWeek,
	rangePastNDays,
	rangePastWeek,
	rangeToday,
	rangeYesterday
} from "@/utils"
import { exportFileFromApi } from "@/utils/excelUtils/excelExport"

import ResetButton from "../../formItems/buttons/reset"
import TextInput from "../../formItems/common/textInput"
import TimeRangePicker from "../../formItems/common/timeRangePicker"
import { TableInfoContainer } from "./styles"
import { columnsTableInformation, GAME, STATE } from "./TableInfo"

const defaultBody = {
	tableId: undefined,
	status: undefined,
	gameTypeId: undefined,
	registerTime: rangePastNDays(90)
}

export const TableInfo: FC<{ data: IMemberParams }> = ({ data }) => {
	const [form] = Form.useForm()
	const { formatMessage, newFormat } = useLocale()
	const { renderFormatWithCurrency } = useDigital()
	const { loading, generalHttpB } = useApi()
	const [bodyExport, setBodyExport] = useState<any>({
		createdStartAt: defaultBody.registerTime ? dayjs(defaultBody?.registerTime[0]).format("YYYY-MM-DD HH:mm:ss") : "",
		createdEndAt: defaultBody.registerTime ? dayjs(defaultBody?.registerTime[1]).format("YYYY-MM-DD HH:mm:ss") : "",
		merchantId: data.merchantId,
		userName: data.userName
	})
	const [dataTableInfo, setDataTableInfo] = useState({} as IMemberList)

	const { pagination, onPageChange } = usePagination(100)
	const [searchParams, setSearchParams] = useState<any>({
		createdStartAt: defaultBody.registerTime ? dayjs(defaultBody?.registerTime[0]).format("YYYY-MM-DD HH:mm:ss") : "",
		createdEndAt: defaultBody.registerTime ? dayjs(defaultBody?.registerTime[1]).format("YYYY-MM-DD HH:mm:ss") : "",
		merchantId: data.merchantId,
		userName: data.userName
	})

	const search = async (value: any) => {
		let formValue = {
			...value,
			...(value.tableCode ? { tableCode: value.tableCode } : {}),
			...(value.gameTypeId ? { gameTypeId: +value.gameTypeId } : {}),
			...(value.status ? { status: [+value.status] } : {}),
			createdStartAt: value.registerTime ? dayjs(value?.registerTime[0]).format("YYYY-MM-DD HH:mm:ss") : "",
			createdEndAt: value.registerTime ? dayjs(value?.registerTime[1]).format("YYYY-MM-DD HH:mm:ss") : "",
			merchantId: data.merchantId,
			userName: data.username
		}
		// Remove properties with empty string values
		formValue = Object.fromEntries(Object.entries(formValue).filter(([_, v]) => v !== "" && v !== undefined))
		delete formValue.registerTime
		setBodyExport(formValue)
		setSearchParams(formValue)
		const [err, tableListRes] = await generalHttpB<any>("/dx-game-data-manager/dxtable/list", { ...formValue, ...pagination })
		if (!err) setDataTableInfo(tableListRes)
	}

	const handleTableInfo = async (isRefresh?: boolean) => {
		const searchValues = {
			...searchParams,
			merchantId: data.merchantId,
			userName: data.username,
			...pagination
		}
		const [err, tableListRes] = await generalHttpB<any>(
			"/dx-game-data-manager/dxtable/list",
			!isRefresh
				? {
						...searchValues
				  }
				: { ...searchValues, pageNum: 1 }
		)
		if (!err) setDataTableInfo(tableListRes)
	}
	const onExportExcel = useCallback(async () => {
		const body = {
			...(bodyExport ? bodyExport : {})
		}
		delete body.pageNum
		delete body.pageSize
		const isExportOk = await exportFileFromApi(
			"https://dxmerchant-fat.ak12.cc/dx-merchant-gateway/dx-game-data-manager/dxtable/member/listExport",
			`会员详情_牌桌列表${dayjs(new Date()).format("YYYYMMDDHHmmss")}.xlsx`,
			{
				...body
			}
		)
		if (isExportOk) {
			Toast.success(newFormat("common.export_success"))
		} else {
			Toast.info(newFormat("common.export_err"))
		}
	}, [bodyExport])

	useEffect(() => {
		// this will help to refresh pagination when upper actions are changed
		if (data.userId) handleTableInfo(true)
	}, [data])
	useEffect(() => {
		handleTableInfo()
	}, [setDataTableInfo, pagination])

	return (
		<TableInfoContainer>
			<CardContainer>
				<QueryForm form={form} initialValues={defaultBody} onFinish={search}>
					<Slot slotname="formItems">
						<TextInput
							normalize={(value: string) => {
								return value.replace(" ", "")
							}}
							labelId={formatMessage({ id: "member.table_info.table_id" }) + ":"}
							placeholderId={formatMessage({ id: "member.table_info.placeholderTableId" }) || ""}
							fieldName="tableCode"
						/>
						<SFormItem name="status" label={`${formatMessage({ id: "member.table_info.state" })}:`}>
							<StyleSelect
								allowClear
								options={STATE(formatMessage)}
								placeholder={formatMessage({ id: "member.table_info.placeholderSelected" })}
								style={{ width: 200 }}
							/>
						</SFormItem>

						<SFormItem name="gameTypeId" label={`${formatMessage({ id: "member.table_info.game_name" })}:`}>
							<StyleSelect
								allowClear
								options={GAME(formatMessage)}
								placeholder={formatMessage({ id: "member.table_info.placeholderSelected" })}
								style={{ width: 200 }}
							/>
						</SFormItem>
						<TimeRangePicker shortcuts={customShortcuts(formatMessage)} label="member.table_info.creation_time" />
					</Slot>

					<Slot slotname="buttons" style={{ width: "100%" }} className="button-container">
						<Flex gap={10}>
							<Button htmlType="submit" type="primary" icon={<SearchOutlined />} loading={loading}>
								{formatMessage({ id: "common.search" })}
							</Button>
							<ResetButton
								onClick={() => {
									form.setFieldsValue(defaultBody)
									form.submit()
								}}
							/>
						</Flex>
					</Slot>
				</QueryForm>
			</CardContainer>

			<Divider />
			{dataTableInfo && (
				<DataList
					data={dataTableInfo.record}
					columns={columnsTableInformation(false, formatMessage, renderFormatWithCurrency)}
					bordered
					size="middle"
					rowKey="tableId"
					pagination={{
						pageSize: dataTableInfo.pageSize,
						current: dataTableInfo.pageNum,
						total: dataTableInfo.totalRecord,
						showSizeChanger: true
					}}
					onChange={onPageChange}
					onExport={onExportExcel}
				/>
			)}
		</TableInfoContainer>
	)
}
export const customShortcuts = (formatMessage: FormatMessageProps) => [
	{
		label: formatMessage({ id: "common.utils.today" }),
		value: rangeToday()
	},
	{
		label: formatMessage({ id: "common.utils.yesterday" }),
		value: rangeYesterday()
	},
	{
		label: formatMessage({ id: "common.utils.last_week" }),
		value: rangeLastWeek()
	},
	{
		label: formatMessage({ id: "common.utils.week_now" }),
		value: rangeCurrentWeek()
	},
	{
		label: formatMessage({ id: "common.utils.last_month" }),
		value: rangeLastMonth()
	},
	{
		label: formatMessage({ id: "common.utils.month1" }),
		value: rangeCurrentMonth()
	},
	{
		label: formatMessage({ id: "common.utils.week1" }),
		value: rangePastWeek()
	},
	{
		label: formatMessage({ id: "common.utils.month1_recent" }),
		value: rangePastNDays(30)
	},
	{
		label: formatMessage({ id: "common.utils.month3_recent" }),
		value: rangePastNDays(90)
	}
]
